// leaflet 地图组件
import * as L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { tdtMapKey, BaseRegionCode, BaseGeoServerType, BaseRegionName, BaseAppCode, mapMaxLevel } from '/@/config/geoserver';
import { getGeoJsonFromGeoserver, ynLandImage, gbnLandImage, getBaseArea, uavOpenImage } from '/@/api/geoserver/map';
import { getUavImageLayerList, getUavImgTimeList } from '/@/api/uav-open';
import { validateNull } from '../utils/validate';

export interface BasicMapProps {
	map?: any;
	mapCenter?: any; //地图中心
	mapZoom?: number; //地图层级
	regionLinesLayer?: any; // 区域边界信息
	widthRegionLayer?: any; //外层边界
	regionNameMarkers?: any[]; // 存放区域显示名称
	timer?: any; //超时时间区分单击和双击
	baseMapLayerGroup?: any; //底图图层
	layerTypeList?: any[];
	uavLayerType?: string;
	uavLayer?: any; //无人机影像图层组
	uavLayerCodes?: any[]; //影像code集合
	singleUavLayerGroup?: any; // 单份成果影像及边界
	uavTimes?: any[]; //无人机影像时间列表
	uavTime?: string; //无人机影像时间
	uavDayTimes?: any[]; //无人机影像日期列表，存放日期 select placeholder 默认 不限日期
	uavDay?: string; //无人机影像日期
	isShowUavTime?: boolean; //是否显示无人机时间
	uavDayObj?: Object; //无人机影像云--日期数组，存放所有日期
	uavDataKey?: String; //无人机影像云--加载影像key
	regionCode?: string; // 当前区域编码,初始值根据默认区域变化
	regionName?: string; //当前区域名称
	regionInfoList?: any[]; //存放区域，用于下钻和返回
	isClickRegion?: boolean; // 是否点击了区域,防止重复点击
	isClickMap?: boolean; //是否点击地图，获取地图定位点数据，用于加载当前地块信息
	latitude?: number | string; //地图点击点坐标
	longitude?: number | string; //地图点击点坐标
	acre_id?: string; //点击点对应的图斑id
	geoserver_acre_info?: any; //点击点对应的图斑数据
	layerGroups?: any; //图层组get，存放所有图层，图层设置不同的层级
	gnqLayer?: any; //粮食功能区图层
	gbnLayer?: any; //高标农图层
	ynLayer?: any; //永农图层
	regionLayer?: any; //
	clickRegionCode?: string; //获取点击的区域code
	clickRegionName?: string; //获取点击的区域name
	isShowSatelliteImage?: boolean; //是否显示卫星影像，默认显示
	isDoubleClick?: boolean; //是否双击
	isLoadOver?: boolean; //地图是否加载完成
	loadingUav?: boolean; // 点击预览-加载无人机影像
	isShowRegionLayer?: boolean; //是否显示区域边界
	defaultSetView?: boolean; //是否默认移动地图中心点
	isDisableMapClick?: boolean;
	markerLayer:any
}

export function useMapMethod(options?: BasicMapProps) {
	const defaultOptions: BasicMapProps = {
		map: null,
		mapCenter: [29.154282, 119.793462], //地图中心
		mapZoom: 10, //地图层级
		regionLinesLayer: null, // 区域边界信息
		widthRegionLayer: null, //外层边界
		regionNameMarkers: [], // 存放区域显示名称
		timer: null, //超时时间区分单击和双击
		baseMapLayerGroup: null, //底图图层
		layerTypeList: ['无人机影像', '卫星影像'],
		uavLayerType: '卫星影像',
		uavLayer: null, //无人机影像图层组
		uavLayerCodes: [], //影像code集合
		singleUavLayerGroup: null, // 单份成果影像及边界
		uavTimes: [], //无人机影像时间列表
		uavTime: '', //无人机影像时间
		uavDayTimes: [], //无人机影像日期列表，存放日期 select placeholder 默认 不限日期
		uavDay: '', //无人机影像日期
		isShowUavTime: false, //是否显示无人机时间
		regionCode: BaseRegionCode.value, // 当前区域编码,初始值根据默认区域变化
		regionName: BaseRegionName.value, //当前区域名称
		regionInfoList: [
			{
				name: BaseRegionName.value,
				regionCode: BaseRegionCode.value,
			},
		], //存放区域，用于下钻和返回
		isClickRegion: false, // 是否点击了区域,防止重复点击
		isClickMap: false, //是否点击地图，获取地图定位点数据，用于加载当前地块信息
		latitude: 0, //地图点击点坐标
		longitude: 0, //地图点击点坐标
		acre_id: '', //点击点对应的图斑id
		geoserver_acre_info: null, //点击点对应的图斑数据
		layerGroups: null, //图层组get，存放所有图层，图层设置不同的层级
		gnqLayer: null, //粮食功能区图层
		gbnLayer: null, //高标农图层
		ynLayer: null, //永农图层
		regionLayer: null, //
		clickRegionCode: '', //获取点击的区域code
		clickRegionName: '', //获取点击的区域name
		isShowSatelliteImage: true, //是否显示卫星影像，默认显示
		isDoubleClick: false, //是否双击
		isLoadOver: false, //地图是否加载完成
		loadingUav: false, // 点击预览-加载无人机影像
		isShowRegionLayer: true, //是否显示区域边界
		defaultSetView: true,
		isDisableMapClick: false,
		markerLayer:null
	};
	//合并基础配置和自定义配置
	const mergeDefaultOptions = (options: any, props: any): BasicMapProps => {
		for (const key in options) {
			if (!Object.getOwnPropertyDescriptor(props, key)) {
				props[key] = options[key];
			}
		}
		return props;
	};
	//合并基础配置和自定义配置
	const mapState = mergeDefaultOptions(defaultOptions, options);
	//地图方法
	const initMap = (mapId: string) => {
		mapState.map = L.map(mapId, {
			crs: L.CRS.EPSG4326,
			center: mapState.mapCenter,
			maxZoom: mapMaxLevel,
			minZoom: 5,
			zoom: mapState.mapZoom,
			zoomControl: false,
			attributionControl: false,
			preferCanvas: true,
			doubleClickZoom: false,
		});
		//添加窗格，把wms图层添加到此窗格中，可以在geojson图层上展示
		mapState.isLoadOver = true;
		mapState.map.createPane('maxLevelPane');
		mapState.map.getPane('maxLevelPane').style.zIndex = 590;
		mapState.map.on('dblclick', function (e: { latlng: { lat: number | undefined; lng: number | undefined } }) {
			//禁用地图点击事件
			if (mapState.isDisableMapClick) {
				return;
			}
			if (!mapState.isShowRegionLayer) {
				return;
			}
			if (mapState.timer) {
				window.clearTimeout(mapState.timer);
				mapState.timer = null;
			}
			//判断是否已经点击区域，防止重复触发
			if (mapState.isClickRegion) {
				mapState.isClickRegion = false;
				return;
			}
			if (mapState.isClickMap) {
				//点击地图，抛出事件
				mapState.latitude = e.latlng.lat || 0;
				mapState.longitude = e.latlng.lng || 0;
				return;
			}
			if (mapState.regionCode == BaseRegionCode.value) {
				return;
			}
			//层级发生变化，清理之前的区域边界和区域名称
			if (mapState.regionLinesLayer) {
				mapState.regionLinesLayer.clearLayers();
			}
			if (mapState.regionNameMarkers.length > 0) {
				mapState.regionNameMarkers.forEach((item) => {
					item.clearLayers();
				});
				mapState.regionNameMarkers = [];
			}
			mapState.regionInfoList.pop();
			let lastRegion = mapState.regionInfoList[mapState.regionInfoList.length - 1];
			mapState.regionCode = lastRegion.regionCode;
			mapState.regionName = lastRegion.name;
			getRegionListWms(mapState.regionCode);
			getRegionListWmsForSingle(mapState.regionCode);
		});
		mapState.map.on('click', function (e: { latlng: { lat: string | number | undefined; lng: string | number | undefined } }) {
			console.log('lat = ' + e.latlng.lat + ';lng = ' + e.latlng.lng);
			//判断是否已经点击区域，防止重复触发
			if (mapState.isClickRegion) {
				mapState.isClickRegion = false;
				return;
			}
			mapState.timer = window.setTimeout(() => {
				if (mapState.isClickMap) {
					//点击地块图层，抛出事件
					mapState.latitude = e.latlng.lat || 0;
					mapState.longitude = e.latlng.lng || 0;
					return;
				}
			}, 300);
		});
		addSateLayer();
		//添加延迟更新地图方法，防止出现因地图容器发生变化而导致的地图显示不全
		setTimeout(() => {
			mapState.map.invalidateSize(true);
		}, 500);
		if (mapState.isShowRegionLayer) {
			getRegionListWms(BaseRegionCode.value);
			getRegionListWmsForSingle(BaseRegionCode.value);
		}
	};
	/**
	 * 添加卫星影像
	 */
	const addSateLayer = () => {
		let layerType = mapState.isShowSatelliteImage ? 'img' : 'vec';
		let labelType = mapState.isShowSatelliteImage ? 'cia' : 'cva';
		if (!mapState.baseMapLayerGroup) {
			mapState.baseMapLayerGroup = new L.LayerGroup();
			mapState.baseMapLayerGroup.addTo(mapState.map);
		} else {
			mapState.baseMapLayerGroup.clearLayers();
		}
		var wMap = L.tileLayer(`https://t{s}.tianditu.gov.cn/DataServer?T=${layerType}_c&x={x}&y={y}&l={z}&tk=${tdtMapKey}`, {
			minZoom: 5,
			maxZoom: mapMaxLevel,
			maxNativeZoom: 17,
			minNativeZoom: 5,
			subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
			zoomOffset: 1,
			tileSize: 256,
		});
		var lMap = L.tileLayer(`https://t{s}.tianditu.gov.cn/DataServer?T=${labelType}_c&x={x}&y={y}&l={z}&tk=${tdtMapKey}`, {
			subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
			zIndex: 3,
			zoomOffset: 1,
			minZoom: 5,
			maxZoom: mapMaxLevel,
			tileSize: 256,
		});
		mapState.baseMapLayerGroup.addLayer(wMap);
		mapState.baseMapLayerGroup.addLayer(lMap);
	};
	/**
	 * 加载单一区域边界
	 * @param code_region
	 */
	const getRegionListWmsForSingle = async (code_region: string) => {
		if (mapState.widthRegionLayer) {
			mapState.map.removeLayer(mapState.widthRegionLayer);
		}
		var regionStyle = {
			color: '#89cfda',
			weight: 5,
			opacity: 1,
			fillColor: '',
			fillOpacity: 0,
		};
		var param = {
			service: 'WFS',
			version: '1.0.0',
			request: 'GetFeature',
			typeName: `${BaseGeoServerType.value}:AR-REGION`,
			maxFeatures: 10000,
			outputFormat: 'application/json',
			CQL_FILTER: `region_code = '${code_region}'`,
		};
		let data = await getGeoJsonFromGeoserver(param);
		var geo_l = L.geoJson(data as any, {
			style: regionStyle,
		}).addTo(mapState.map);
		geo_l.bringToBack(); //放到底层
		mapState.widthRegionLayer = geo_l;
		var zoom = 10;
		if (code_region.length == 9) {
			zoom = 12;
		} else if (code_region.length == 12) {
			zoom = 13;
		}
		var center = [data.features[0].properties.latitude, data.features[0].properties.longitude];
		mapState.defaultSetView && mapState.map.setView(center, zoom);
	};
	/**
	 * 加载区域边界
	 * @param code_region
	 */
	const getRegionListWms = (code_region: string) => {
		if (!mapState.regionLinesLayer) {
			mapState.regionLinesLayer = new L.LayerGroup();
			mapState.regionLinesLayer.addTo(mapState.map);
		}
		var regionStyle = {
			color: '#89cfda',
			weight: 1,
			opacity: 1,
			fillColor: '#2c5ba9',
			fillOpacity: mapState.isShowSatelliteImage ? 0 : 1,
		};
		var param = {
			service: 'WFS',
			version: '1.0.0',
			request: 'GetFeature',
			typeName: `${BaseGeoServerType.value}:AR-REGION`,
			maxFeatures: 10000,
			outputFormat: 'application/json',
			CQL_FILTER: `parent_code = '${code_region}'`,
		};
		getGeoJsonFromGeoserver(param).then((res) => {
			var data = res;
			if (data.features.length > 0) {
				var markerArray: any[] = [];
				var geo_l = L.geoJson(data, {
					onEachFeature: function (
						feature: { geometry: { type: string }; properties: { latitude: any; longitude: any; name: any } },
						layer: { setStyle: (arg0: { color: string; weight: number; opacity: number; fillColor: string; fillOpacity: number }) => void }
					) {
						if (feature.geometry.type === 'MultiPolygon' || feature.geometry.type === 'Polygon') {
							layer.setStyle(regionStyle);
							var center = {
								lat: feature.properties.latitude,
								lng: feature.properties.longitude,
							};
							var content = `<div style='color:#ffffff;width:32px;margin-left: -16px;font-size:12px;'>${feature.properties.name}</div>`;
							var icon_div = L.divIcon({
								html: content,
								className: 'town_name',
							});
							let marker = L.marker(center, {
								icon: icon_div,
								clickable: false,
								draggable: false,
							});
							markerArray.push(marker);
						}
					},
				}).addTo(mapState.map);
				mapState.regionLinesLayer.addLayer(geo_l);
				let markerGroup = L.layerGroup(markerArray);
				mapState.map.addLayer(markerGroup);
				mapState.regionNameMarkers.push(markerGroup);
				geo_l.on('dblclick', function (e: { sourceTarget: { feature: { properties: { region_code: any; name: any } } } }) {
					//禁用地图点击事件
					if (mapState.isDisableMapClick) {
						return;
					}
					mapState.isDoubleClick = true;
					if (mapState.timer) {
						window.clearTimeout(mapState.timer);
						mapState.timer = null;
					}
					//判断是否是点击地图获取经纬度
					if (mapState.isClickMap) {
						return;
					}
					//防止地图重复触发双击事件
					mapState.isClickRegion = true;
					var code = e.sourceTarget.feature.properties.region_code;
					var name = e.sourceTarget.feature.properties.name;
					//到村结束
					if (code.length == 12) {
						return;
					}
					mapState.regionCode = code;
					mapState.regionName = name;
					mapState.regionInfoList.push({
						name: name,
						regionCode: code,
					});
					if (mapState.regionLinesLayer) {
						mapState.regionLinesLayer.clearLayers();
					}
					if (mapState.regionNameMarkers.length > 0) {
						mapState.regionNameMarkers.forEach((item) => {
							item.clearLayers();
						});
						mapState.regionNameMarkers = [];
					}
					getRegionListWms(code);
					getRegionListWmsForSingle(code);
				});
				geo_l.on('click', function (e: { sourceTarget: { feature: { properties: any } } }) {
					//判断是否是点击地图获取经纬度
					if (mapState.isClickMap) {
						return;
					}
					mapState.isClickRegion = true;
					mapState.timer = window.setTimeout(() => {
						if (mapState.isDoubleClick) {
							mapState.isDoubleClick = false;
							return;
						}
						var prop = e.sourceTarget.feature.properties;
						if (prop.grade != '3' && prop.grade != '4') return;
						mapState.clickRegionCode = prop.region_code;
						mapState.clickRegionName = prop.name;
					}, 300);
				});
				geo_l.on('mouseover', function (e: { sourceTarget: any }) {
					var layer = e.sourceTarget;
					layer.setStyle({
						weight: 3,
						fillColor: '#2d6fb7',
						fillOpacity: mapState.isShowSatelliteImage ? 0 : 1,
					});
				});
				geo_l.on('mouseout', function (e: { sourceTarget: any }) {
					var layer = e.sourceTarget;
					layer.setStyle({
						weight: 1,
						fillColor: '#2c5ba9',
						fillOpacity: mapState.isShowSatelliteImage ? 0 : 1,
					});
				});
			}
		});
	};

	//#region  无人机影像相关接口
	/**
	 * 无人机时间切换
	 */
	const handleUavTimeChange = () => {
		if (mapState.uavLayer) {
			mapState.uavLayer.clearLayers();
		}
		getUavDayList();
		init_open_uav();
	};
	/**
	 * 无人机日期切换
	 */
	const handleUavDayChange = () => {
		if (mapState.uavLayer) {
			mapState.uavLayer.clearLayers();
		}
		init_open_uav();
	};
	/**
	 * 无人机和卫星影像切换
	 * @param e
	 */
	const handleUavLayerChange = (e: string) => {
		console.log('e', e);
		if (e == '卫星影像') {
			if (mapState.uavLayer) {
				mapState.uavLayer.clearLayers();
			}
			mapState.isShowUavTime = false;
			mapState.map.setMaxZoom(mapMaxLevel);
		} else {
			if (mapState.uavLayer) {
				mapState.uavLayer.clearLayers();
			}
			mapState.isShowUavTime = true;
			if (mapState.uavTime) {
				getUavDayList();
				init_open_uav();
			}
		}
	};
	/**
	 * 无人机影像云--获取时间列表
	 * @param regionCode
	 * @param townName
	 * @param tagIds
	 * @param needDay
	 */
	const getUavTimeList = (regionCode = BaseRegionCode.value, townName = '', tagIds = [], needDay = 1) => {
		setTimeout(async () => {
			const data = await getUavImgTimeList({
				regionCode,
				townName,
				needDay,
				tagIds: tagIds.length > 0 ? tagIds.join(',') : '',
			});
			if (data && data.code == 0) {
				mapState.uavDataKey = data.data.dataKey;
				let dateList = data.data.dataList;
				let list = [];
				let month_day_obj = {};
				dateList.forEach((item) => {
					month_day_obj = {
						...month_day_obj,
						...item.month,
					};
					let monthList = Object.keys(item.month);
					monthList.forEach((item_m) => {
						let time_str = `${item.year}-${item_m}`;
						if (list.findIndex((e) => e == time_str) == -1) {
							list.push(time_str);
						}
					});
				});
				mapState.uavTimes = list;
				mapState.uavTime = list.length > 0 ? list[0] : '';
				mapState.uavDayObj = month_day_obj;
				if (mapState.isShowUavTime) {
					handleUavTimeChange();
				}
			}
		}, 2000);
	};
	/**
	 * 无人机影像云 -- 获取日期列表
	 * @returns
	 */
	const getUavDayList = () => {
		if (validateNull(mapState.uavTime)) return;
		mapState.uavDay = '';
		let temp_list = mapState.uavTime.split('-');
		let month = temp_list[1];
		mapState.uavDayTimes = mapState.uavDayObj[month];
	};
	/**
	 * 无人机影像云 -- 获取影像列表
	 * @returns
	 */
	const init_open_uav = async () => {
		if (validateNull(mapState.uavTime)) return;
		if (!mapState.uavLayer) {
			mapState.uavLayer = new L.LayerGroup();
			mapState.uavLayer.addTo(mapState.map);
		}
		let temp_list = mapState.uavTime.split('-');
		let param = {
			dataKey: mapState.uavDataKey,
			year: temp_list[0],
			month: temp_list[1],
		};
		if (mapState.uavDay) {
			param = Object.assign(param, {
				day: mapState.uavDay,
			});
		}
		const data = await getUavImageLayerList(param);
		if (data && data.code == 0) {
			let baseMapRegionCode = '';
			let wms = data.data.dataList.map((o) => {
				let temp_array = o.layerName.split(':');
				baseMapRegionCode = temp_array[0];
				return temp_array[1];
			});
			if (wms.length > 0) {
				if (wms.length > 5) {
					var array: any[] = [];
					wms.forEach((item, index) => {
						array.push(item);
						if (index == wms.length - 1) {
							let wmsLayer = uavOpenImage(array, baseMapRegionCode);
							wmsLayer.setZIndex(90);
							wmsLayer.options.maxZoom = mapMaxLevel;
							mapState.uavLayer.addLayer(wmsLayer);
							mapState.map.setMaxZoom(mapMaxLevel);
							array = [];
						} else if (array.length >= 5) {
							let wmsLayer = uavOpenImage(array, baseMapRegionCode);
							wmsLayer.setZIndex(90);
							wmsLayer.options.maxZoom = mapMaxLevel;
							mapState.uavLayer.addLayer(wmsLayer);
							mapState.map.setMaxZoom(mapMaxLevel);
							array = [];
						}
					});
				} else {
					let wmsLayer = uavOpenImage(wms, baseMapRegionCode);
					wmsLayer.setZIndex(90);
					wmsLayer.options.maxZoom = mapMaxLevel;
					mapState.uavLayer.addLayer(wmsLayer);
					mapState.map.setMaxZoom(mapMaxLevel);
				}
			}
		}
	};

	const removeUavLayers = () => {
		if (mapState.uavLayer) {
			mapState.uavLayer.clearLayers();
		}
	}

	//#endregion

	/**
	 * 获取点击点地块信息
	 * @param layerName
	 * @param viewparams
	 */
	const getLandImgInfo = async (layerName: string, viewparams: string) => {
		var param = {
			service: 'WFS',
			version: '1.0.0',
			request: 'GetFeature',
			typeName: `${BaseGeoServerType.value}:${layerName}`,
			maxFeatures: 10,
			outputFormat: 'application/json',
			CQL_FILTER: `CONTAINS(geom,SRID=4326;POINT(${mapState.longitude} ${mapState.latitude}))`,
			viewparams,
		};
		let data = await getGeoJsonFromGeoserver(param, `${BaseGeoServerType.value}:${layerName}`);
		if (data.features.length > 0) {
			var item = data.features[0];
			mapState.geoserver_acre_info = item;
		}
	};
	/**
	 * 加载永农图层
	 */
	const getYnWms = () => {
		if (!mapState.layerGroups) {
			mapState.layerGroups = new L.LayerGroup();
			mapState.layerGroups.addTo(mapState.map);
		}
		if (mapState.ynLayer) {
			mapState.layerGroups.addLayer(mapState.ynLayer);
			return;
		}
		var wmsLayer = ynLandImage();
		wmsLayer.setParams({
			styles: 'farmLandStyle',
		});
		wmsLayer.setZIndex(100);
		mapState.ynLayer = wmsLayer;
		mapState.layerGroups.addLayer(wmsLayer);
	};
	/**
	 * 移除永农图层
	 */
	const removeYnWms = () => {
		return mapState.ynLayer && mapState.layerGroups.removeLayer(mapState.ynLayer);
	};
	/**
	 * 加载高标农图层
	 * @returns
	 */
	const getGbnWms = () => {
		if (!mapState.layerGroups) {
			mapState.layerGroups = new L.LayerGroup();
			mapState.layerGroups.addTo(mapState.map);
		}
		if (mapState.gbnLayer) {
			mapState.layerGroups.addLayer(mapState.gbnLayer);
			return;
		}
		var wmsLayer = gbnLandImage();
		wmsLayer.setParams({
			styles: 'blueStyle',
		});
		wmsLayer.setZIndex(110);
		mapState.gbnLayer = wmsLayer;
		mapState.layerGroups.addLayer(wmsLayer);
	};
	/**
	 * 移除高标农图层
	 * @returns
	 */
	const removeGbnWms = () => {
		return mapState.gbnLayer && mapState.layerGroups.removeLayer(mapState.gbnLayer);
	};

	/**
	 * 获取客户所有监管区域
	 * @param {*} sql
	 * @returns
	 */
	const getCustomerAllArea = (sql = '') => {
		return new Promise(async (reslove) => {
			var param = {
				service: 'WFS',
				version: '1.0.0',
				request: 'GetFeature',
				typeName: `${BaseGeoServerType.value}:dm_tree_base`,
				maxFeatures: 1000,
				outputFormat: 'application/json',
				CQL_FILTER: sql,
			};
			let data = await getGeoJsonFromGeoserver(param, `${BaseGeoServerType.value}:dm_tree_base`);
			if (data && data.features.length > 0) {
				let layers = [];
				var item = data.features[0];
				// if (!item.geometry) {
				// 	reslove([]);
				// }
				(item?.geometry?.coordinates || []).forEach((o, index) => {
					let latlngs = [];
					latlngs = L.GeoJSON.coordsToLatLngs(o[0]);
					const polygon = L.polygon(latlngs, {
						color: '#ffffff',
						weight: 3,
						opacity: 1,
						fillOpacity: 0,
						fillColor: '#0084FF',
						pane: 'maxLevelPane',
						maxFeatures: 600,
						info: item.properties,
						index: index,
						pmIgnore: true,
					});
					layers.push(polygon);
				});

				reslove(layers);
			}
		});
	};
	/**
	 * 获取基地图层
	 * @param sql
	 */
	const getTreeBaseWms = (sql = '') => {
		if (!mapState.layerGroups) {
			mapState.layerGroups = new L.LayerGroup();
			mapState.layerGroups.addTo(mapState.map);
		}
		if (mapState.gbnLayer) {
			mapState.layerGroups.clearLayers();
		}
		var wmsLayer = getBaseArea();
		wmsLayer.setParams({
			styles: 'blueStyle',
			CQL_FILTER: sql,
		});
		mapState.layerGroups.addLayer(wmsLayer);
	};
	/**
	 * 在地图中地位
	 * @param latlngs 
	 * latlngs = [[lat1,lng1],[lat2,lng2]...]
	 */
	const setViewForMap = (latlngs:any) =>{
		latlngs = latlngs.filter((o:Array<Number>) => o[0] && o[1])
		if(latlngs.length == 0) return
		if(latlngs.length == 1){
			mapState.map && mapState.map.setView(latlngs[0])
		}else{
			mapState.map && mapState.map.fitBounds(latlngs)
		}
	}



	const removeMap = () => {
		if (mapState.regionLinesLayer) {
			mapState.regionLinesLayer.clearLayers();
		}
		if (mapState.regionNameMarkers.length > 0) {
			mapState.regionNameMarkers.forEach((item) => {
				item.clearLayers();
			});
			mapState.regionNameMarkers = [];
		}
		if (mapState.layerGroups) {
			mapState.layerGroups.clearLayers();
			mapState.layerGroups = null;
		}
		if (mapState.uavLayer) {
			mapState.uavLayer.clearLayers();
			mapState.uavLayer = null;
		}
		if (mapState.ynLayer) {
			mapState.ynLayer = null;
		}
		if (mapState.gnqLayer) {
			mapState.gnqLayer = null;
		}
		if (mapState.gbnLayer) {
			mapState.gbnLayer = null;
		}
		if(mapState.markerLayer){
			mapState.markerLayer.clearLayers()
			mapState.markerLayer = null
		}

		if (mapState.map) {
			mapState.map.remove();
		}
	};

	return {
		initMap,
		removeMap,
		removeGbnWms,
		getGbnWms,
		removeYnWms,
		getYnWms,
		getLandImgInfo,
		handleUavLayerChange,
		handleUavDayChange,
		handleUavTimeChange,
		getUavTimeList,
		getCustomerAllArea,
		getTreeBaseWms,
		setViewForMap,
		removeUavLayers
	};
}
